package utils;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    //Druid连接池
    private static DruidDataSource dataSource;

    static {
        //1、获取到流文件
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
        //2、加载流文件
        Properties properties = new Properties();
        try {
            properties.load(is);
            //3、获取到配置文件信息
            String driver = properties.getProperty("driverClassName");
            String url = properties.getProperty("url");
            String user = properties.getProperty("username");
            String passwd = properties.getProperty("password");
            Class.forName(driver);
            System.out.println("驱动注册成功");
//            conn = DriverManager.getConnection(url, name, passwd);
//            System.out.println(conn);
//            System.out.println("数据库连接成功");

            //创建Druid连接池
            dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driver);
            dataSource.setUrl(url);
            dataSource.setUsername(user);
            dataSource.setPassword(passwd);
            dataSource.setInitialSize(5);
            dataSource.setMaxActive(20);
            dataSource.setMinIdle(5);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConn(){
        try {
            Connection conn = dataSource.getConnection();//获取数据库连接
//            System.out.println(conn);
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static DataSource getDataSource(){
//        System.out.println(dataSource);
        return dataSource;
    }
}
